﻿using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
using System.Reflection;
using System.Runtime.InteropServices;
using Excel;
using System.IO;

namespace Ketoan
{
	/// <summary>
	/// Summary description for Report.
	/// </summary>
	public class frmReport_kt : System.Windows.Forms.Form
	{
		//Language lan = new Language();
		ReportDocument oRpt;
		Excel.Application oxl;
		Excel._Workbook owb;
		Excel._Worksheet osheet;
		public bool bPrinter;
		private LibKetoan.AccessData a;	
		private string ReportFile;
		private DataSet ds=new DataSet();
		private System.Data.DataTable dt=new System.Data.DataTable();
		private CrystalDecisions.Windows.Forms.CrystalReportViewer Report;

		private string s_Tenbaocao, s_Ngaythang, s_Tinhchat, s_Giatri11, s_Giatri12, s_Giatri21, s_Giatri22, s_Giatri31, s_Giatri32;
		private string s_Giatri41, s_Giatri42, s_Giatri51, s_Giatri52;//, s_Giatri61, s_Giatri62, s_Giatri71, s_Giatri72, s_Giatri81, s_Giatri82;

		private System.Windows.Forms.NumericUpDown banin;
		private System.Windows.Forms.Label label1;
		private System.Windows.Forms.Button butKetthuc;
		private System.Windows.Forms.Button butIn;
		private System.Windows.Forms.NumericUpDown den;
		private System.Windows.Forms.Label label3;
		private System.Windows.Forms.NumericUpDown tu;
		private System.Windows.Forms.Label label2;
		private System.Windows.Forms.Button butExcel;
		private System.Windows.Forms.Button butPdf;
		private string ExportPath;
		ExportOptions crExportOptions;
		DiskFileDestinationOptions crDiskFileDestinationOptions;
		/// <summary>
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.Container components = null;


		public frmReport_kt(LibKetoan.AccessData acc,DataSet ds_Data,string s_Tieude,string s_Ngay,string s_Tc,string s_GT11,string s_GT12,string s_GT21,string s_GT22,string s_GT31,string s_GT32,string s_GT41,string s_GT42,string s_GT51,string s_GT52,string sReport)
		{
			InitializeComponent();
			a=acc;
			ds=ds_Data;
			s_Tenbaocao=s_Tieude;
			s_Ngaythang=s_Ngay;
			s_Tinhchat=s_Tc;
			s_Giatri11=s_GT11;
			s_Giatri12=s_GT12;
			s_Giatri21=s_GT21;
			s_Giatri22=s_GT22;
			s_Giatri31=s_GT31;
			s_Giatri32=s_GT32;
			s_Giatri41=s_GT41;
			s_Giatri42=s_GT42;
			s_Giatri51=s_GT51;
			s_Giatri52=s_GT52;
			ReportFile=sReport;
			this.Text=s_Tieude + " ("+sReport+")";
		}

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>

		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if(components != null)
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
			try
			{
				GC.Collect();
				oRpt.Dispose();
				ds.Dispose();
				dt.Dispose();
				Report.Dispose();
			}
			catch{}	;

		}

		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(frmReport_kt));
			this.Report = new CrystalDecisions.Windows.Forms.CrystalReportViewer();
			this.banin = new System.Windows.Forms.NumericUpDown();
			this.label1 = new System.Windows.Forms.Label();
			this.butKetthuc = new System.Windows.Forms.Button();
			this.butIn = new System.Windows.Forms.Button();
			this.den = new System.Windows.Forms.NumericUpDown();
			this.label3 = new System.Windows.Forms.Label();
			this.tu = new System.Windows.Forms.NumericUpDown();
			this.label2 = new System.Windows.Forms.Label();
			this.butExcel = new System.Windows.Forms.Button();
			this.butPdf = new System.Windows.Forms.Button();
			((System.ComponentModel.ISupportInitialize)(this.banin)).BeginInit();
			((System.ComponentModel.ISupportInitialize)(this.den)).BeginInit();
			((System.ComponentModel.ISupportInitialize)(this.tu)).BeginInit();
			this.SuspendLayout();
			// 
			// Report
			// 
			this.Report.ActiveViewIndex = -1;
			this.Report.DisplayGroupTree = false;
			this.Report.Location = new System.Drawing.Point(0, 5);
			this.Report.Name = "Report";
			this.Report.ReportSource = null;
			this.Report.Size = new System.Drawing.Size(305, 100);
			this.Report.TabIndex = 9;
			// 
			// banin
			// 
			this.banin.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
			this.banin.Location = new System.Drawing.Point(374, 5);
			this.banin.Minimum = new System.Decimal(new int[] {
																  1,
																  0,
																  0,
																  0});
			this.banin.Name = "banin";
			this.banin.Size = new System.Drawing.Size(34, 21);
			this.banin.TabIndex = 1;
			this.banin.Value = new System.Decimal(new int[] {
																1,
																0,
																0,
																0});
			this.banin.KeyDown += new System.Windows.Forms.KeyEventHandler(this.banin_KeyDown);
			// 
			// label1
			// 
			this.label1.Location = new System.Drawing.Point(306, 5);
			this.label1.Name = "label1";
			this.label1.Size = new System.Drawing.Size(65, 23);
			this.label1.TabIndex = 0;
			this.label1.Text = "&Số bản in :";
			this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
			// 
			// butKetthuc
			// 
			this.butKetthuc.DialogResult = System.Windows.Forms.DialogResult.Cancel;
			this.butKetthuc.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
			this.butKetthuc.Image = ((System.Drawing.Bitmap)(resources.GetObject("butKetthuc.Image")));
			this.butKetthuc.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
			this.butKetthuc.Location = new System.Drawing.Point(750, 4);
			this.butKetthuc.Name = "butKetthuc";
			this.butKetthuc.Size = new System.Drawing.Size(72, 23);
			this.butKetthuc.TabIndex = 8;
			this.butKetthuc.Text = "Kết thúc";
			this.butKetthuc.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
			this.butKetthuc.Click += new System.EventHandler(this.butKetthuc_Click);
			// 
			// butIn
			// 
			this.butIn.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
			this.butIn.Image = ((System.Drawing.Bitmap)(resources.GetObject("butIn.Image")));
			this.butIn.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
			this.butIn.Location = new System.Drawing.Point(581, 4);
			this.butIn.Name = "butIn";
			this.butIn.Size = new System.Drawing.Size(51, 23);
			this.butIn.TabIndex = 6;
			this.butIn.Text = "      In";
			this.butIn.Click += new System.EventHandler(this.butIn_Click);
			// 
			// den
			// 
			this.den.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
			this.den.Location = new System.Drawing.Point(535, 5);
			this.den.Name = "den";
			this.den.Size = new System.Drawing.Size(44, 21);
			this.den.TabIndex = 5;
			this.den.KeyDown += new System.Windows.Forms.KeyEventHandler(this.banin_KeyDown);
			// 
			// label3
			// 
			this.label3.Location = new System.Drawing.Point(505, 5);
			this.label3.Name = "label3";
			this.label3.Size = new System.Drawing.Size(29, 23);
			this.label3.TabIndex = 4;
			this.label3.Text = "đến :";
			this.label3.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
			// 
			// tu
			// 
			this.tu.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
			this.tu.Location = new System.Drawing.Point(458, 5);
			this.tu.Name = "tu";
			this.tu.Size = new System.Drawing.Size(45, 21);
			this.tu.TabIndex = 3;
			this.tu.KeyDown += new System.Windows.Forms.KeyEventHandler(this.banin_KeyDown);
			// 
			// label2
			// 
			this.label2.Location = new System.Drawing.Point(403, 5);
			this.label2.Name = "label2";
			this.label2.Size = new System.Drawing.Size(55, 23);
			this.label2.TabIndex = 2;
			this.label2.Text = "Từ trang :";
			this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
			// 
			// butExcel
			// 
			this.butExcel.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
			this.butExcel.Image = ((System.Drawing.Bitmap)(resources.GetObject("butExcel.Image")));
			this.butExcel.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
			this.butExcel.Location = new System.Drawing.Point(633, 4);
			this.butExcel.Name = "butExcel";
			this.butExcel.Size = new System.Drawing.Size(60, 23);
			this.butExcel.TabIndex = 7;
			this.butExcel.Text = "      Excel";
			this.butExcel.Click += new System.EventHandler(this.butExcel_Click);
			// 
			// butPdf
			// 
			this.butPdf.FlatStyle = System.Windows.Forms.FlatStyle.Popup;
			this.butPdf.Image = ((System.Drawing.Bitmap)(resources.GetObject("butPdf.Image")));
			this.butPdf.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
			this.butPdf.Location = new System.Drawing.Point(694, 4);
			this.butPdf.Name = "butPdf";
			this.butPdf.Size = new System.Drawing.Size(55, 23);
			this.butPdf.TabIndex = 14;
			this.butPdf.Text = "      PDF";
			this.butPdf.Click += new System.EventHandler(this.butPdf_Click);
			// 
			// frmReport_kt
			// 
			this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
			this.CancelButton = this.butKetthuc;
			this.ClientSize = new System.Drawing.Size(1016, 713);
			this.Controls.AddRange(new System.Windows.Forms.Control[] {
																		  this.butPdf,
																		  this.butExcel,
																		  this.den,
																		  this.tu,
																		  this.banin,
																		  this.label3,
																		  this.label2,
																		  this.label1,
																		  this.butKetthuc,
																		  this.butIn,
																		  this.Report});
			this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
			this.KeyPreview = true;
			this.Name = "frmReport_kt";
			this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
			this.Text = "Medisoft";
			this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
			this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.frmReport_KeyDown);
			this.Load += new System.EventHandler(this.frmReport_Load);
			this.Closed += new System.EventHandler(this.frmReport_Closed);
			((System.ComponentModel.ISupportInitialize)(this.banin)).EndInit();
			((System.ComponentModel.ISupportInitialize)(this.den)).EndInit();
			((System.ComponentModel.ISupportInitialize)(this.tu)).EndInit();
			this.ResumeLayout(false);

		}
		#endregion

		private void frmReport_Load(object sender, System.EventArgs e)
		{
			this.Report.Size = new System.Drawing.Size(Screen.PrimaryScreen.WorkingArea.Width,Screen.PrimaryScreen.WorkingArea.Height);
			this.Size= new System.Drawing.Size(Screen.PrimaryScreen.WorkingArea.Width,Screen.PrimaryScreen.WorkingArea.Height);
			this.Tag=System.Environment.CurrentDirectory.ToString();
			string dir = System.IO.Directory.GetCurrentDirectory();
			ExportPath = "";
			int j = 0;
			for (int i = 0; i < dir.Length; i++)
			{
				if (dir.Substring(i, 1) == "\\") j++;
				if (j == 2) break;
				ExportPath += dir.Substring(i, 1);
			}
			ExportPath += "\\pdf\\";
			if (!System.IO.Directory.Exists(ExportPath)) System.IO.Directory.CreateDirectory(ExportPath);
			PreviewReport();
		}

		private void PreviewReport()
		{
			try
			{
				oRpt=new ReportDocument();
				oRpt.Load("..\\..\\..\\report\\"+ReportFile,OpenReportMethod.OpenReportByTempCopy);
				oRpt.SetDataSource(ds);
				oRpt.DataDefinition.FormulaFields["SoYTe"].Text="'"+a.Syte+"'";
				oRpt.DataDefinition.FormulaFields["BenhVien"].Text="'"+a.Tenbv+"'";
				oRpt.DataDefinition.FormulaFields["Tenbaocao"].Text="'"+s_Tenbaocao+"'";
				oRpt.DataDefinition.FormulaFields["Ngaythang"].Text="'"+s_Ngaythang+"'";
				oRpt.DataDefinition.FormulaFields["Tinhchat"].Text="'"+s_Tinhchat+"'";
				oRpt.DataDefinition.FormulaFields["Giatri11"].Text="'"+s_Giatri11+"'";
				oRpt.DataDefinition.FormulaFields["Giatri12"].Text="'"+s_Giatri12+"'";
				oRpt.DataDefinition.FormulaFields["Giatri21"].Text="'"+s_Giatri21+"'";
				oRpt.DataDefinition.FormulaFields["Giatri22"].Text="'"+s_Giatri22+"'";
				oRpt.DataDefinition.FormulaFields["Giatri31"].Text="'"+s_Giatri31+"'";
				oRpt.DataDefinition.FormulaFields["Giatri32"].Text="'"+s_Giatri32+"'";
				oRpt.DataDefinition.FormulaFields["Giatri41"].Text="'"+s_Giatri41+"'";
				oRpt.DataDefinition.FormulaFields["Giatri42"].Text="'"+s_Giatri42+"'";
				oRpt.DataDefinition.FormulaFields["Giatri51"].Text="'"+s_Giatri51+"'";
				oRpt.DataDefinition.FormulaFields["Giatri52"].Text="'"+s_Giatri52+"'";
//				oRpt.PrintOptions.PaperSize=PaperSize.PaperA4;
//				if (bDoc) oRpt.PrintOptions.PaperOrientation=PaperOrientation.Portrait;
//				else oRpt.PrintOptions.PaperOrientation=PaperOrientation.Landscape;
				Report.ReportSource=oRpt;
			}
			catch (Exception e)
			{
				MessageBox.Show ("The following error was discovered: '"+e.Message+"'. It was occured in '"+e.StackTrace+"'", "Report Viewer",MessageBoxButtons.OK, MessageBoxIcon.Error);				
			}
		}		

		private void frmReport_Closed(object sender, System.EventArgs e)
		{
			try
			{
				System.Environment.CurrentDirectory=this.Tag.ToString();
				GC.Collect();
				this.Dispose();
				ds.Dispose();
				dt.Dispose();
				Report.Dispose();
			}
			catch{}	;
		}	


		private void butKetthuc_Click(object sender, System.EventArgs e)
		{
			bPrinter=false;
			this.Dispose();
			this.Close();
		}

		private void butIn_Click(object sender, System.EventArgs e)
		{
			Cursor=Cursors.WaitCursor;
			bPrinter=true;
			try
			{
				oRpt.PrintToPrinter(Convert.ToInt16(banin.Value),false,Convert.ToInt16(tu.Value),Convert.ToInt16(den.Value));
			}
			catch(Exception ex){MessageBox.Show(ex.Message);}
			Cursor=Cursors.Default;
			this.Close();
		}

		private void frmReport_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
		{
			switch (e.KeyCode)
			{
				case Keys.F5: butPdf_Click(sender, e); break;
				case Keys.F9: butIn_Click(sender,e);break;
				case Keys.F7: butExcel_Click(sender,e);break;
				case Keys.F10: butKetthuc_Click(sender,e);break;
			}
		}

		private void banin_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
		{
			if (e.KeyCode==Keys.Enter) SendKeys.Send("{Tab}");
		}

		private void quitExcel()
		{
			//owb.Close(true, null, null);
			//oxl.Quit();

			if (osheet != null)
			{
				System.Runtime.InteropServices.Marshal.ReleaseComObject(osheet);
			}
			if (owb != null)
			{
				System.Runtime.InteropServices.Marshal.ReleaseComObject(owb);
			}
			if (oxl != null)
			{
				System.Runtime.InteropServices.Marshal.ReleaseComObject(oxl);
			}

			osheet = null;
			owb = null;
			oxl = null;

			GC.Collect();
		}

		private void butExcel_Click(object sender, System.EventArgs e)
		{
			a.check_process_Excel();
			//string tenfile=(b_baohiem)?a.Export_Excel(dt,ReportFile.Substring(0,ReportFile.Length-4)):a.Export_Excel(ds,ReportFile.Substring(0,ReportFile.Length-4));
			string tenfile=a.Export_Excel(ds,ReportFile.Substring(0,ReportFile.Length-4));
			oxl=new Excel.Application();
			owb=(Excel._Workbook)(oxl.Workbooks.Open(tenfile,Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value));
			osheet=(Excel._Worksheet)owb.ActiveSheet;
			oxl.ActiveWindow.DisplayGridlines=true;
			oxl.ActiveWindow.DisplayZeros=false;
			osheet.PageSetup.Orientation=XlPageOrientation.xlLandscape;
			osheet.PageSetup.PaperSize=XlPaperSize.xlPaperA4;
			osheet.PageSetup.LeftMargin=20;
			osheet.PageSetup.RightMargin=20;
			osheet.PageSetup.TopMargin=30;
			osheet.PageSetup.CenterFooter="Trang : &P/&N";
			oxl.Visible=true;
			quitExcel();
		}

		private void butPdf_Click(object sender, System.EventArgs e)
		{
			string tenfile = ReportFile.ToLower().Replace(".rpt", "");
			tenfile = ExportPath + tenfile + ".pdf";
			crDiskFileDestinationOptions = new DiskFileDestinationOptions();
			crExportOptions = oRpt.ExportOptions;
			crDiskFileDestinationOptions.DiskFileName = tenfile;
			crExportOptions.DestinationOptions = crDiskFileDestinationOptions;
			crExportOptions.ExportDestinationType = ExportDestinationType.DiskFile;
			crExportOptions.ExportFormatType = ExportFormatType.PortableDocFormat;
			oRpt.Export();
			try
			{
				string filerun = "AcroRd32.exe", arg = tenfile;
				if (System.IO.File.Exists(arg))
				{
					backup f = new backup(filerun, arg, true);
					f.Launch();
				}
			}
			catch
			{
				MessageBox.Show("Tập tin :" + tenfile);
			}	
		}
	}
}